#coding=utf-8

import cgi
import re
import urllib
import string
import random
import time
import datetime
import math
from Cookie import SimpleCookie
from collections import deque
from operator import itemgetter
from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import urlfetch
from google.appengine.ext import db

class TermPath(db.Model):
  term = db.StringProperty(required=True)
  queryTime = db.DateTimeProperty(auto_now_add=True)
  browserId = db.StringProperty(required=True)
  lastTerm = db.StringProperty()
  lang = db.StringProperty()


class SetLang(webapp.RequestHandler):
  def get(self):
    c = SimpleCookie()
    c.load(self.request.cookies)
    lr = self.request.get('lr')
    if lr == "":
	    if not c.has_key("lr"):
		    lr = "lang_en";
	    else:
		    lr = self.request.cookies["lr"];
    else:
	    c = SimpleCookie()
	    c["lr"] = lr
	    c["lr"]["expires"]= time.time() + 86400 * 365
	    c["lr"]["path"]="/"   
	    header_value = c["lr"].output(header='').lstrip()
	    self.response.headers._headers.append(('Set-Cookie', header_value))

    self.response.out.write("""<html>
        <head>
	<title>assoword</title>
	</head>
        <body>
	    <form action="/lr" method="get">
	    <div>current: """+ lr[5:] +"""</div>
            <div><select name="lr"><option value="lang_af" >Afrikaans</option><option value="lang_ar" >Arabic</option><option value="lang_hy" >Armenian</option><option value="lang_be" >Belarusian</option><option value="lang_bg" >Bulgarian</option><option value="lang_ca" >Catalan</option><option value="lang_zh-CN" >Chinese&nbsp;(Simplified)</option><option value="lang_zh-TW" >Chinese&nbsp;(Traditional)</option><option value="lang_hr" >Croatian</option><option value="lang_cs" >Czech</option><option value="lang_da" >Danish</option><option value="lang_nl" >Dutch</option><option value="lang_en">English</option><option value="lang_eo" >Esperanto</option><option value="lang_et" >Estonian</option><option value="lang_tl" >Filipino</option><option value="lang_fi" >Finnish</option><option value="lang_fr" >French</option><option value="lang_de" >German</option><option value="lang_el" >Greek</option><option value="lang_iw" >Hebrew</option><option value="lang_hu" >Hungarian</option><option value="lang_is" >Icelandic</option><option value="lang_id" >Indonesian</option><option value="lang_it" >Italian</option><option value="lang_ja" >Japanese</option><option value="lang_ko" >Korean</option><option value="lang_lv" >Latvian</option><option value="lang_lt" >Lithuanian</option><option value="lang_no" >Norwegian</option><option value="lang_fa" >Persian</option><option value="lang_pl" >Polish</option><option value="lang_pt" >Portuguese</option><option value="lang_ro" >Romanian</option><option value="lang_ru" >Russian</option><option value="lang_sr" >Serbian</option><option value="lang_sk" >Slovak</option><option value="lang_sl" >Slovenian</option><option value="lang_es" >Spanish</option><option value="lang_sw" >Swahili</option><option value="lang_sv" >Swedish</option><option value="lang_th" >Thai</option><option value="lang_tr" >Turkish</option><option value="lang_uk" >Ukrainian</option><option value="lang_vi" >Vietnamese</option></select> <input type="submit"> </div>
            </form>
	</body>
      </html>""")


class MainPage(webapp.RequestHandler):

  def get(self):

	# get
	word1=''
	word2=''
	lang=''
	self.request.charset='utf-8'
	query = db.Query(TermPath)
	query.filter('queryTime >', datetime.datetime.today() - datetime.timedelta(1) )
	query.order('-queryTime')
	termList = query.fetch(limit=1)
	for term in termList:
		#self.response.out.write( str(term.queryTime) + " ")
		word1=term.lastTerm
		word2=term.term
		lang=term.lang

    	self.response.out.write("""<html><head><title>assoword: Hello World!</title></head><body>
<form action="/q" method="get">
 <div><h2><em>assoword</em> could help people to catch current popular concepts about any query</h2></div>
 <div><input type="text" name="q" size="31"> <input type="submit"></div>
</form>""")

	if not word1 == '':
		self.response.out.write( "<div> Lastest query:""")  
		self.response.out.write( "<a href=\"q?q=%s&lr=%s\">%s</a> / " % (word1 ,lang ,word1))
		self.response.out.write( "<a href=\"q?q=%s&lr=%s\">%s</a>" % (word2 ,lang ,word2))
    		self.response.out.write("""</div>""")
	
	self.response.out.write("""<hr>
<div>
<h3>search summarized-web generated in <em>assoword</em></h3> 
<style type="text/css">
@import url(http://www.google.com/cse/api/branding.css);
</style>
<div class="cse-branding-right" style="background-color:#FFFFFF;color:#000000">
  <div class="cse-branding-form">
    <form action="http://www.google.com/cse" id="cse-search-box">
      <div>
        <input type="hidden" name="cx" value="partner-pub-0000633222751680:lmrxdp-h0de" />
        <input type="hidden" name="ie" value="UTF-8" />
        <input type="text" name="q" size="31" />
        <input type="submit" name="sa" value="Search" />
      </div>
    </form>
  </div>
  <div class="cse-branding-logo">
    <img src="http://www.google.com/images/poweredby_transparent/poweredby_FFFFFF.gif" alt="Google" />
  </div>
  <div class="cse-branding-text">
    Custom Search
  </div>
</div>
</div> 	  
</body></html>""")



class Test(webapp.RequestHandler):
  def get(self):
	self.request.charset='utf-8'
	#self.response.out.write( str(datetime.datetime.today() - datetime.timedelta(1)) + " ")
  	# db
	query = db.Query(TermPath)
	query.filter('queryTime >', datetime.datetime.today() - datetime.timedelta(1) )
	query.order('-queryTime')
	termList = query.fetch(limit=1)
	for term in termList:
		self.response.out.write( str(term.queryTime) + " ")
		self.response.out.write( term.lastTerm + " ")
		self.response.out.write( term.term + "<br>")


class QueryPath(webapp.RequestHandler):
  def get(self):
	  # cookie
	  if self.request.cookies:
		browserId = self.request.cookies["bId"];
	  	# db
		termList = db.GqlQuery("SELECT * FROM TermPath WHERE browserId = :1", browserId)
		for term in termList:
			self.response.out.write( term.queryTime.strftime("%Y/%m/%d") + " ")
			self.response.out.write( term.lastTerm + " ")
			self.response.out.write( term.term + "<br>")
	  else:
		self.response.out.write("no query record for this user")


class QueryNext(webapp.RequestHandler):
  def get(self):
	  self.request.charset='utf-8'
	  q = self.request.get('q')
	  # db
	  termList = db.GqlQuery("SELECT * FROM TermPath WHERE lastTerm = :1", q)
	  for term in termList:
		  self.response.out.write( term.term + "<br>")


class Query(webapp.RequestHandler):
  dbytes = {}  
  dbytes['lang_zh-TW']=1
  dbytes['lang_zh-CN']=1
  dbytes['lang_ja']=1
  dbytes['lang_ko']=1
  dbytes['lang_th']=1
  
  def yahooapi(self ,q ,lr):
	appid = ""
	final = {}
	url = ""
	
	q = urllib.quote(q.encode('utf8'))
	url = ( "http://boss.yahooapis.com/ysearch/web/v1/\"%s\"?appid=%s&abstract=long&count=50&style=raw&lang=%s&region=%s" % (str(q) ,appid ,"tzh" ,"tw"))

	# fetch 
	result = urlfetch.fetch(url)
	if not result.status_code == 200:
		self.response.out.write('fail')
		return (url ,final)
	
	# term extract
	word = {} #tf
	df = {}   #doc frequent
	d = deque()
	ret = str(result.content).decode("utf8")
	#self.response.out.write(ret)
	jDecode = simplejson.JSONDecoder()
	x = jDecode.decode(ret)
	doc = 1000
	for xx in x["ysearchresponse"]["resultset_web"]:
		#self.response.out.write(y["abstract"])
		y = xx["title"] + "" + xx["abstract"]
		doc = doc - 1

		hadInDoc = {}
		strlength = len(y)
		z = 0
		en_len = 0
		word_len = 0	
		
		# NON CJK
		if not lr in self.dbytes:
			#self.response.out.write(y + 'xx<p>')
			last1word = ''
			last2word = ''
			pos = 0 
			for substr1 in sp.split(y):
				substr = substr1.lower()
				if substr in word:
					word[substr] = word[substr] + 1
					if not substr in hadInDoc:
						df[substr] = df[substr] + 1
						hadInDoc[substr] = 1
				else:
					word[substr] = 1
					df[substr] = 1

				# for tri-gram
				pos = pos + 1
				if pos >= 3:
					longword1 = last1word + ' '  + substr
					longword2 = last2word + ' '  + longword1
					# for next
					last2word = last1word
					last1word = substr
				else:
					if pos == 2:
						longword1 = last1word + ' '  + substr
						longword2 = ''
						# for next
						last2word = last1word
						last1word = substr
					else:
						longword1 = ''
						longword2 = ''
						# for next
						last1word = substr
					
				if longword1 in word:
					word[longword1] = word[longword1] + 1
					if not longword1 in hadInDoc:
						df[longword1] = df[longword1] + 1
						hadInDoc[longword1] = 1
				else:
					word[longword1] = 1
					df[longword1] = 1

				if longword2 in word:
					word[longword2] = word[longword2] + 1
					if not longword2 in hadInDoc:
						df[longword2] = df[longword2] + 1
						hadInDoc[longword2] = 1
				else:
					word[longword2] = 1
					df[longword2] = 1

			continue
			
		# CJK
		while z < strlength :
			d.clear()
			word_len = 0
			w = z + 1
			while w <= strlength :

				if re.match('\s', y[w-1:w])  :
					w = w + 1;
					word_len = word_len + 1
					substr = y[z:w-1].strip()
					if substr in word:
						word[substr] = word[substr] + 1
						if not substr in hadInDoc:
							df[substr] = df[substr] + 1
							hadInDoc[substr] = 1
					else:
						word[substr] = 1
						df[substr] = 1
						#self.response.out.write('<font color=red>'+substr + '</font> ,')
					d.append(en_len + 1)
					en_len = 0
					continue
				
				if re.match('\w', y[w-1:w])  :
					en_len = en_len + 1
					w = w + 1
					continue
				
				if (w - z > 2) and re.match('\w', y[w-2:w-1]) :
					word_len = word_len + 1
					substr = y[z:w-1].strip()
					if substr in word:
						word[substr] = word[substr] + 1
						if not substr in hadInDoc:
							df[substr] = df[substr] + 1
							hadInDoc[substr] = 1
					else:
						word[substr] = 1
						df[substr] = 1
					#self.response.out.write('<font color=red>'+substr + '</font> ,')
					d.append(en_len)
					en_len = 0
				
				word_len = word_len + 1
				substr = y[z:w].strip()
				
				if (w - z == 0):
					w = w + 1
					continue
					
				if word_len > 5 :
					break
					
				if substr in word:
					#word[substr] = word[substr] + 1 + word_len + doc
					word[substr] = word[substr] + 1 
					if not substr in hadInDoc:
						df[substr] = df[substr] + 1
						hadInDoc[substr] = 1
				else:
					word[substr] = 1
					df[substr] = 1
				
				#self.response.out.write('<font color=red>'+substr + '</font> ,')
				w = w + 1

			if re.match('\w', y[z:z+1]) and len(d)  :
				z = z + d.popleft()
			else:
				z = z + 1

	# decease weight of substring for CJK
	if True and lr in self.dbytes:
		tmpf = {}
		for k, v in word.iteritems():
			l = len(k)
			if l < 2:
				continue
			tmpf[k] = l
		for k, v in sorted( tmpf.items(), key=itemgetter(1),  reverse=False ) :
			sub1 = k[:-1]
			sub2 = k[1:]
			if sub1 in word and word[sub1] == word[k]:
				word[sub1] = 1
				#self.response.out.write(k + ':' + sub1 + '<br>')
			if sub2 in word and word[sub2] == word[k]:
				word[sub2] = 1
				#self.response.out.write(k + ':' + sub2 + '<br>')

	#freq
	if True:
		for k, v in word.iteritems():
			if v > 2 and len(k) > 1 :
				final[k] = v
	#tfidf
	if False:
		docAmount = 1000 - doc;
		for k, tf in word.iteritems():
			if tf > 2 and len(k) > 1 :
				#tfidf = tf / df[k]
				#tfidf = tf * docAmount / df[k]
				tfidf = tf * math.log(docAmount/df[k])
				final[k] = math.floor(tfidf)
	# end of yahooapi
	return (url  ,final)

  def googweb(self ,q ,lr):
	final = {}
	url = ""
	
	q = urllib.quote(q.encode('utf8'))
	base_url = 'http://www.google.com.tw/search?hl=en&lr=' + lr + '&ie=utf-8&oe=utf-8&num=100&q='
	url = base_url + str(q)

	# fetch 
	#url = "http://tw.yahoo.com"
	result = urlfetch.fetch(url)
	if not result.status_code == 200:
		self.response.out.write('fail')
		return (url ,final)

	# term extract
	word = {} #tf
	df = {}   #doc frequent
	d = deque()
	ret = str(result.content).decode("utf8")
	#self.response.out.write(ret)
	#ret = str("").decode("utf8")
	rp = re.compile('<b>\.\.\.</b>|<em>|</em>|<cite>.*?</cite>')
	p = re.compile('\||\.\.\.|&middot;|<.*?>')
	sp = re.compile('\s|,|\.')
	doc = 1000
 	for x in ret.split('<li class=g>'):
		if re.match("<h3", x) is None :
			continue
		x1 = rp.sub('',x)
		
		for y in p.split(x1):
			if re.match("1\spost|\d+\sposts|\(function\(\)|if\(google\.|\&|\s\]|\s\-|Cached|Similar pages|Translate this page|More results from|\.\.\.",y) :
				continue

			#self.response.out.write(y + '<p>')	
			#self.response.out.write(len(y))
			#self.response.out.write('<p>')
			doc = doc - 1

			hadInDoc = {}
			strlength = len(y)
			z = 0
			en_len = 0
			word_len = 0	
		
			# NON CJK
			if not lr in self.dbytes:
				#self.response.out.write(y + 'xx<p>')
				last1word = ''
				last2word = ''
				pos = 0 
				for substr1 in sp.split(y):
					substr = substr1.lower()
					if substr in word:
						word[substr] = word[substr] + 1
						if not substr in hadInDoc:
							df[substr] = df[substr] + 1
							hadInDoc[substr] = 1
					else:
						word[substr] = 1
						df[substr] = 1

					# for tri-gram
					pos = pos + 1
					if pos >= 3:
						longword1 = last1word + ' '  + substr
						longword2 = last2word + ' '  + longword1
						# for next
						last2word = last1word
						last1word = substr
					else:
						if pos == 2:
							longword1 = last1word + ' '  + substr
							longword2 = ''
							# for next
							last2word = last1word
							last1word = substr
						else:
							longword1 = ''
							longword2 = ''
							# for next
							last1word = substr
					
					if longword1 in word:
						word[longword1] = word[longword1] + 1
						if not longword1 in hadInDoc:
							df[longword1] = df[longword1] + 1
							hadInDoc[longword1] = 1
					else:
						word[longword1] = 1
						df[longword1] = 1

					if longword2 in word:
						word[longword2] = word[longword2] + 1
						if not longword2 in hadInDoc:
							df[longword2] = df[longword2] + 1
							hadInDoc[longword2] = 1
					else:
						word[longword2] = 1
						df[longword2] = 1

				continue
			
			# CJK
			while z < strlength :
				d.clear()
				word_len = 0
				w = z + 1
				while w <= strlength :

					if re.match('\s', y[w-1:w])  :
						w = w + 1;
						word_len = word_len + 1
						substr = y[z:w-1].strip()
						if substr in word:
							word[substr] = word[substr] + 1
							if not substr in hadInDoc:
								df[substr] = df[substr] + 1
								hadInDoc[substr] = 1
						else:
							word[substr] = 1
							df[substr] = 1
							#self.response.out.write('<font color=red>'+substr + '</font> ,')
						d.append(en_len + 1)
						en_len = 0
						continue
					
					if re.match('\w', y[w-1:w])  :
						en_len = en_len + 1
						w = w + 1
						continue
					
					if (w - z > 2) and re.match('\w', y[w-2:w-1]) :
						word_len = word_len + 1
						substr = y[z:w-1].strip()
						if substr in word:
							word[substr] = word[substr] + 1
							if not substr in hadInDoc:
								df[substr] = df[substr] + 1
								hadInDoc[substr] = 1
						else:
							word[substr] = 1
							df[substr] = 1
						#self.response.out.write('<font color=red>'+substr + '</font> ,')
						d.append(en_len)
						en_len = 0
					
					word_len = word_len + 1
					substr = y[z:w].strip()
					
					if (w - z == 0):
						w = w + 1
						continue
					
					if word_len > 5 :
						break
					
					if substr in word:
						#word[substr] = word[substr] + 1 + word_len + doc
						word[substr] = word[substr] + 1 
						if not substr in hadInDoc:
							df[substr] = df[substr] + 1
							hadInDoc[substr] = 1
					else:
						word[substr] = 1
						df[substr] = 1
					
					#self.response.out.write('<font color=red>'+substr + '</font> ,')
					w = w + 1

				if re.match('\w', y[z:z+1]) and len(d)  :
					z = z + d.popleft()
				else:
					z = z + 1
				#self.response.out.write('<font color=green>'+ str(z) + '</font> ,')

	# sorting & filter #######################################

	# decease weight of substring for CJK
	if True and lr in self.dbytes:
		tmpf = {}
		for k, v in word.iteritems():
			l = len(k)
			if l < 2:
				continue
			tmpf[k] = l
		for k, v in sorted( tmpf.items(), key=itemgetter(1),  reverse=False ) :
			sub1 = k[:-1]
			sub2 = k[1:]
			if sub1 in word and word[sub1] == word[k]:
				word[sub1] = 1
				#self.response.out.write(k + ':' + sub1 + '<br>')
			if sub2 in word and word[sub2] == word[k]:
				word[sub2] = 1
				#self.response.out.write(k + ':' + sub2 + '<br>')

	#freq
	if True:
		for k, v in word.iteritems():
			if v > 2 and len(k) > 1 :
				final[k] = v
	#tfidf
	if False:
		docAmount = 1000 - doc;
		for k, tf in word.iteritems():
			if tf > 2 and len(k) > 1 :
				#tfidf = tf / df[k]
				#tfidf = tf * docAmount / df[k]
				tfidf = tf * math.log(docAmount/df[k])
				final[k] = math.floor(tfidf)
	# end of googweb
	return (url  ,final)

  def renderAPI(self ,final):
    	self.response.out.write("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"></head><body>")
    	jEncode = simplejson.JSONEncoder()
	self.response.out.write(jEncode.encode(final))
    	self.response.out.write("</body></html>")
	return
  
  def renderM(self ,q ,final ,lr ,oq ):
	
    	self.response.out.write("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"><title>"+ q +" @ assoword help people to catch current popular concepts about any query</title></head><body>")
	self.response.out.write( q + ' @ assoword <div>')
	
	wordNum = 0
	for k, v in sorted( final.items(), key=itemgetter(1),  reverse=True ) :
		if wordNum >= 300:
			break
		wordNum = wordNum + 1
		# url encode
		urls='q?q=' + k + '&lr=' + lr + '&lq=' + oq + '&m=m' 
		urls=urls.encode('utf8')
		urls=urllib.quote(urls,'?&=')
		self.response.out.write( '<a href="' + urls + '">' + k + '</a> / ')#('+ str(v) +') ' )
	
	self.response.out.write( ' </div>')
	self.response.out.write( ' <div>')
	self.response.out.write( ' <div style="float: left;">')
	self.response.out.write( q)
	self.response.out.write( ' @ [' + lr[5:7] + ']<font size=-3><a href="/lr" target=_blank>change</a></font>')
	self.response.out.write( '<br>')
	self.response.out.write( '<font size=-2> <a href="/qp" target=_blank>My Query Path</a>')
	self.response.out.write( ' / <a href="/qn?q='+ q +'" target=_blank>Next Query</a>')
	self.response.out.write( """ </div>
	<div align=right> 
<form action="/q" method="get">
New query <input type="text" name="q" size="15"> <input type="submit">
</form> </div>
</div>""" )
    	self.response.out.write("""</body>
</html>""")
	return


  def get(self):

	self.request.charset='utf-8'
	q = self.request.get('q')
	oq = self.request.get('q')  # origTerm
	lq = self.request.get('lq') # lastTerm

	# cookie
	c = SimpleCookie()
	c.load(self.request.cookies)
	
	# lang
	lr = self.request.get('lr')
	
	if c.has_key("lr"):
		lr = self.request.cookies["lr"];
	else:
		if lr == "":
			lr = "lang_en"
			c["lr"] = lr
			c["lr"]["expires"]= str(time.time() + 86400 * 365)
			c["lr"]["path"]="/"   
			header_value = c["lr"].output(header='').lstrip()
			self.response.headers._headers.append(('Set-Cookie', header_value))

	# bid
	if not c.has_key("bId"):
		browserId = random.randint(1,10000000)
	  	c["bId"] = str(browserId)
	  	c["bId"]["expires"]= str(time.time() + 60*60)
	  	c["bId"]["path"]="/"
		header_value = c["bId"].output(header='').lstrip()
		self.response.headers._headers.append(('Set-Cookie', header_value))
	else:
		browserId = self.request.cookies["bId"];
	  
	# db
	term = TermPath(term = oq,
			browserId = str(browserId),
			lastTerm = lq,
			lang = lr)
	term.put();

	# call web-word-segmentation
	url = {} #tf
	final = {}   #doc frequent
	url ,final = self.googweb(q ,lr)
	if len(final) == 0:
		# backup call
		url ,final = self.yahooapi(q ,lr)

	# mobile render
	m = self.request.get('m')
	if m == "m":
		self.renderM(q, final, lr, oq)
		return
	
	if m == "api":
		self.renderAPI(final)
		return

	# render
	#self.response.out.write("<!-- " + lr + ":" + str(browserId) + " //-->")
	#self.response.out.write("<!-- " + str(self.request.cookies) + " //-->")
    	self.response.out.write("<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"><title>"+ q +" @ assoword help people to catch current popular concepts about any query</title></head><body>")
	self.response.out.write( '<div><em>assoword</em> <font size=-2>could help people to catch current popular concepts about any query</font></div>')
	self.response.out.write( ' <div>')
	self.response.out.write( ' <div style="float: left;">')
	self.response.out.write( q)
	self.response.out.write( ' @ [' + lr[5:7] + ']<font size=-3><a href="/lr" target=_blank>change</a></font>')
	self.response.out.write( '<br>')
	self.response.out.write( '<font size=-2> <a href="/qp" target=_blank>My Query Path</a>')
	self.response.out.write( ' / <a href="/qn?q='+ q +'" target=_blank>Next Query</a>')
	self.response.out.write( ' / <a href="'+ url +'">Web search</a> </font>')
	self.response.out.write( """ </div>
	<div align=right> 
<form action="/q" method="get">
New query <input type="text" name="q" size="15"> <input type="submit">
</form> </div>
 </div>
 <div><hr>
<div STYLE="FLOAT: right; MARGIN: 15PX">
<script type="text/javascript"><!-- 
google_ad_client = "pub-0000633222751680";
/* 160x600, created 5/18/09 */
google_ad_slot = "7702785022";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
</div>""" )
	
	wordNum = 0
	for k, v in sorted( final.items(), key=itemgetter(1),  reverse=True ) :
		#if wordNum >= 300:
			#break
		wordNum = wordNum + 1
		# url encode
		urls='q?q=' + k + '&lr=' + lr + '&lq=' + oq  
		urls=urls.encode('utf8')
		urls=urllib.quote(urls,'?&=')
		self.response.out.write( '<a href="' + urls + '">' + k + '</a> / ')#('+ str(v) +') ' )
		#self.response.out.write( '<a href="' + urls + '">' + k + '</a>('+ str(v) +') ' )
	
    	self.response.out.write("""</div></body>
</html>""")



def main():
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
					('/t', Test),
					('/qp', QueryPath),
					('/qn', QueryNext),
					('/lr', SetLang),
					('/q', Query)],
                                       debug=True)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()

